package com.aaa.rabbitmq.three;

import com.aaa.rabbitmq.one.util.RabbitMQUtil;
import com.aaa.rabbitmq.one.util.SleepUtil;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息应答机制
 * 这是一个工作线程 02   相当于一个消费者
 */
public class Work03 {
    //队列名称
    public static final String TASK_QUEUE_NAME="ack_queue";
    //接收消息
    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = RabbitMQUtil.getChannel();
        System.out.println("w2等待消息接受时间较长。。。。。。");

        //声明接受消息
        DeliverCallback deliverCallback = (var1, msg) -> {
            //接受消息先睡眠一秒
            SleepUtil.sleep(10);

            /**
             * 手动确认
             * 1,消息标记 消息属性  2,是否批量应答
             */
            channel.basicAck(msg.getEnvelope().getDeliveryTag(),false);
            System.out.println("w2工作线程消费消息"+new String(msg.getBody()));

        };
        //取消消息的回调
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println(consumerTag+"消息消费被中断");
        };

//        //设置不公平分发  (设置为1就是不公平分发)
//        channel.basicQos(1);
        //设置预取值
        channel.basicQos(2);
        //手动应答
        boolean autoAck = false;

        //消费消息
        channel.basicConsume(TASK_QUEUE_NAME, autoAck, deliverCallback, cancelCallback);
    }

}
